import {
  Body,
  Controller,
  Delete,
  ForbiddenException,
  Get,
  Param,
  Post,
  Put,
  Query,
  Response,
  StreamableFile,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import * as ExcelJS from 'exceljs';
import { Buffer } from 'buffer';
import { createReadStream } from 'fs';
import { join } from 'path';
import { TransformInterceptor } from 'src/interceptor/intersform.interceptor';
import {
  CreateErrorLianluDto,
  ExportExcelDto,
  QueryListDto,
} from './dto/errorLianlu.dto';
import { ErrorLianluService } from './errorLianlu.service';
import { FilesInterceptor } from '@nestjs/platform-express';

@Controller('/errorLianlu')
export class ErrorLianluController {
  constructor(protected readonly errorLianluService: ErrorLianluService) {}

  @Get()
  @UseInterceptors(new TransformInterceptor())
  async getErrorLianluList(@Query() params: QueryListDto) {
    const queryData = Object.assign(
      { pageSize: 10, pageNumber: 1, recordDateStart: '', recordDateEnd: '' },
      params,
    );
    // 获取数据
    const res = await this.errorLianluService.getErrorLianluList(queryData);
    // 获取数据总数
    const total = await this.errorLianluService.getErrorLianluCount(queryData);
    return {
      message: '获取成功',
      data: res,
      total,
    };
  }

  @Get('/lianluDataNumber')
  @UseInterceptors(new TransformInterceptor())
  async getErrorLianluNumber() {
    const res = await this.errorLianluService.getErrorLianluNumber();
    return {
      data: res,
      message: '获取成功',
    };
  }

  @Post()
  @UseInterceptors(new TransformInterceptor())
  async addErrorLianlu(@Body() data: CreateErrorLianluDto) {
    const res = await this.errorLianluService.addErrorLianlu([data]);
    return {
      data: res,
      message: '添加成功',
    };
  }
  // 根据id删除链路
  @Delete(':id')
  @UseInterceptors(new TransformInterceptor())
  async removeLianlu(@Param('id') id: string) {
    if (await this.errorLianluService.getErrorLianluById(id)) {
      const res = await this.errorLianluService.delErrorLianlu(id);
      return {
        data: res,
        message: '删除成功',
      };
    } else {
      return {
        data: [],
        message: `id为${id}的链路信息不存在！`,
        code: 405,
      };
    }
  }

  @Put(':id')
  @UseInterceptors(new TransformInterceptor())
  async updataErrorLianlu(
    @Param('id') id: string,
    @Body() data: CreateErrorLianluDto,
  ) {
    if (await this.errorLianluService.getErrorLianluById(id)) {
      const res = await this.errorLianluService.updataLianlu(id, data);
      return {
        message: '更新成功',
        data: res,
      };
    } else {
      return {
        data: [],
        message: `id为${id}的链路信息不存在！`,
        code: 405,
      };
    }
  }

  @Post('/export')
  @UseInterceptors(new TransformInterceptor())
  async exportExcel(@Body() data: ExportExcelDto) {
    return {
      data: await this.errorLianluService.exportExcle(data),
      message: '导出成功',
    };
  }

  @Get('/installModule')
  getFile(@Response({ passthrough: true }) res: any): StreamableFile {
    const file = createReadStream(join(process.cwd(), '../module.xlsx'));
    res.set({
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition':
        'attachment; filename="' +
        encodeURIComponent('省局总局链路监控汇总') +
        '.xlsx"',
    });
    return new StreamableFile(file);
  }

  @Post('/errorLianluFile')
  @UseInterceptors(FilesInterceptor('file'))
  async insetErrorLianluByFile(@UploadedFiles() file: any) {
    const getProjectCell = (target, key, value) => {
      const handler = {
        1: (target: CreateErrorLianluDto, value: string) => {
          target.lianlu_code = value;
        },
        2: (target, value) => {
          target.lianlu_name = value;
        },
        3: (target, value) => {
          target.lianlu_start = value;
        },
        4: (target, value) => {
          target.lianlu_end = value;
        },
        5: (target, value) => {
          target.error_time_start = value;
        },
        6: (target, value) => {
          target.error_time_end = value;
        },
        7: (target, value) => {
          target.error_reason = value;
        },
        8: (target, value) => {
          target.plan_error = value;
        },
        9: (target, value) => {
          target.record_date = value;
        },
      };
      handler[key] && handler[key](target, value);
    };
    const { buffer } = file[0];
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(buffer); // 加载buffer文件
    const worksheet = workbook.getWorksheet(1); // 获取excel表的第一个sheet
    const fileData = [] as CreateErrorLianluDto[];
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 1) {
        const target = {} as CreateErrorLianluDto;
        row.eachCell((cell, colNumber) => {
          getProjectCell(target, colNumber, cell.value);
        });
        fileData.push(target);
      }
    });
    const res = await this.errorLianluService.addErrorLianlu(fileData);
    return {
      data: res,
      code: 200,
      message: '添加成功！',
    };
  }
}
